<template>
  <h2>通知公告管理页面</h2>
  <el-button type="primary" @click="handlerAdd">添加通知公告</el-button>

  <!-- 添加通知公告的弹框 -->
  <el-dialog v-model="dialogAddFormVisible" :title="dialogTitle" width="500">
    <el-form :model="addFormData">
      <el-form-item label="通知公告标题" :label-width="200">
        <el-input v-model="addFormData.title" autocomplete="off" />
      </el-form-item>

      <el-form-item label="通知公告标题内容" :label-width="200">
        <el-input v-model="addFormData.content" autocomplete="off" />
      </el-form-item>

      <!-- 通知分类的下拉菜单--数据-从分类接口中请求来 -->
      <el-form-item label="Zones" :label-width="200">
        <el-select v-model="addFormData.categoryId" placeholder="Please select a zone">
          <!--  :label="item.name" 下拉菜单 name -->
          <!--  :value="item._id" 下拉菜单 控制选中对应下拉菜单以后得到的值 -->
          <el-option
            v-for="item in noticeCateArr"
            :key="item._id"
            :label="item.name"
            :value="item._id"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogAddFormVisible = false">取消</el-button>
        <el-button type="primary" @click="noticeAddBtnHandler()"> 确定 </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 列表数据 -->
  <el-table :data="tableData" style="width: 100%">
    <el-table-column prop="title" label="标题" width="180" />
    <el-table-column prop="content" label="内容" width="180" />
    <el-table-column prop="categoryId.name" label="分类" />
    <el-table-column label="操作">
      <template #default="scope">
        <el-button size="small" @click="handleEdit(scope.row)"> 编辑 </el-button>
        <el-button size="small" type="danger" @click="handleDelete(scope.row)"> 删除 </el-button>
      </template>
    </el-table-column>
  </el-table>
</template>
<script setup lang="ts">
import type { IResData } from '@/api/userAPI'
import {
  noticeAddRequest,
  noticeCateListRequest,
  noticeDelByIdRequest,
  noticeListRequest,
  noticeUpdateByIdRequest,
  type INoticeItem,
  type INoticeListItemRes,
} from '../../api/noticeAPI'
import type { AxiosError } from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { computed, ref } from 'vue'

/*
  添加通知公告的功能
*/
const dialogAddFormVisible = ref(false)
const addFormData = ref<INoticeItem>({
  title: '',
  content: '',
  categoryId: '',
  _id: '',
  createTime: '',
  updateTime: '',
})
// 保存通知公告分类的数据
const noticeCateArr = ref<INoticeListItemRes[]>([])
// 请求通知公告分类的接口数据
async function loadNoticeCate() {
  const res = await noticeCateListRequest(1, 100)
  console.log(res.data.data.list)
  //保存分类数据到数组中
  noticeCateArr.value = res.data.data.list
}
//添加表单的保存按钮
async function noticeAddBtnHandler() {
  if (isStatus.value == 'add') {
    try {
      //状态码 是200 执行这里
      const res = await noticeAddRequest(addFormData.value)
      console.log(res)
      if (res.data.code == '200') {
        ElMessage.success('添加成功')
      } else {
        ElMessage.success('添加失败:' + res.data.message)
      }
      dialogAddFormVisible.value = false
    } catch (error) {
      // 状态码 超出200以后就执行这里
      // Error
      // catch 中 error对象-一般都是用Error类创建出来 （Error接口）
      // console.error(error)
      ElMessage.success('添加失败:' + (error as Error).message)

      dialogAddFormVisible.value = false
    }
  } else {
    // addFormData.value._id!
    // ! 非空断言（非nuul 非undefined）
    // noticeUpdateByIdRequest(addFormData.value._id!, {
    //   title: addFormData.value.title,
    //   content: addFormData.value.content,
    // })
    try {
      await noticeUpdateByIdRequest(addFormData.value._id as string, {
        title: addFormData.value.title,
        content: addFormData.value.content,
        categoryId: addFormData.value.categoryId,
      })
      ElMessage.success('修改成功')
      // 刷新列表
      loadNoticeList()
      //隐藏弹框
      dialogAddFormVisible.value = false
    } catch (error) {
      ElMessage.error(
        '修改失败:' +
          (error as AxiosError).message +
          ' ' +
          (error as AxiosError<IResData<number>>).response?.data.message,
      )
      dialogAddFormVisible.value = false
      console.log(error)
    }
  }
}

loadNoticeCate()

/*

  通知公告 列表功能

*/
const tableData = ref<INoticeItem[]>()

async function loadNoticeList() {
  const res = await noticeListRequest()
  console.log(res.data)
  // res.data.data.list
  tableData.value = res.data.data.list
}

// 变量 记录页面处于 添加和编辑状态
const isStatus = ref<'edit' | 'add'>('add')
// 计算属性--根据isStatus的值计算出 弹框的标题
const dialogTitle = computed(() => {
  if (isStatus.value == 'add') {
    return '添加通知公告'
  } else {
    return '编辑通知公告'
  }
})

function handleEdit(item: INoticeItem) {
  console.log(item)
  // 点击编辑修改状态
  isStatus.value = 'edit'
  dialogAddFormVisible.value = true

  // 把要编辑的数据，展示 编辑表单中
  addFormData.value.title = item.title
  addFormData.value.content = item.content
  // INoticeListItemRes
  addFormData.value.categoryId = (item.categoryId as INoticeListItemRes)._id
  //要编辑数据的id
  addFormData.value._id = item._id
}

function handlerAdd() {
  // 点击添加修改状态
  isStatus.value = 'add'
  dialogAddFormVisible.value = true
}

function handleDelete(item: INoticeItem) {
  ElMessageBox.confirm('确定要删除吗', '警告', {
    confirmButtonText: 'OK',
    cancelButtonText: 'Cancel',
    type: 'error',
  })
    .then(async () => {
      const res = await noticeDelByIdRequest(item._id)
      if (res.data.code == '200') {
        loadNoticeList()
        ElMessage.success('删除成功')
      } else {
        ElMessage.success('删除失败')
      }
    })
    .catch(() => {
      ElMessage.success('删除失败')
    })
}

loadNoticeList()
</script>
<style lang="css" scoped></style>
